package webservices;

import interfaces.ICourseQuery;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;

import webservices.helper.Helper;

public class CourseQueryImpl implements ICourseQuery {

	@Override
	public String query(String userID) {
		String returnMessage = "";
		Connection con = null;
		try {
			con = Helper.getDBConnection();
			
			HashMap<String, Boolean> favCourse = new HashMap<String, Boolean>();
			
			ResultSet rs = null;
			rs = con.createStatement().executeQuery("select courseid from favourite where userid = " + userID);
			while (rs.next()){
				favCourse.put(rs.getString("courseID"), true);
			}
			
			returnMessage = "<response name='success' />";
			rs = con.createStatement().executeQuery("select * from course");
			while (rs.next()){
				returnMessage += "<response name='course'>";
				returnMessage += "<courseID>" + rs.getString("courseID") + "</courseID>";
				returnMessage += "<name>" + rs.getString("name") + "</name>";
				returnMessage += "<description>" + rs.getString("description") + "</description>";
				returnMessage += "<teacher>" + rs.getString("teacher") + "</teacher>";
				returnMessage += "<favourite>" + (favCourse.get(rs.getString("courseID")) == null ? "false" : "true") + "</favourite>";
				returnMessage += "</response>";
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try{
				con.close();
			}catch(SQLException e) {}
		}
		return returnMessage;
	}
}
